package com.lonely.fx.spinner;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Spinner;
import javafx.scene.control.SpinnerValueFactory;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.StringConverter;

/**
 * @date: 2022-07-19 21:16
 * @author: ztkj-hzb
 * @description: 文本框(类似h5的数字框效果) --  基于对象，这里重点要使用 valueFactory
 **/
public class SpinnerWithObjectSettingMain extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    /**
     *
     */
    @Override
    public void start(Stage primaryStage) throws Exception {

        HBox hBox = new HBox();

        //定义一个list
        User user1 = new User().setName("小明").setAge(20);
        User user2 = new User().setName("小天").setAge(30);
        User user3 = new User().setName("小地").setAge(40);
        User user4 = new User().setName("小玄").setAge(50);
        User user5 = new User().setName("小黄").setAge(60);
        ObservableList<User> list = FXCollections.observableArrayList(user1, user2, user3, user4, user5);

        //Spinner<User> listSpinner = new Spinner<>(list);
        Spinner<User> listSpinner = new Spinner<>();

        //设置递增，递减按钮的样式
        listSpinner.getStyleClass().add(Spinner.STYLE_CLASS_ARROWS_ON_RIGHT_HORIZONTAL);

        //对于对象类型，展示在页面上的是tostring()，如何调整
        SpinnerValueFactory.ListSpinnerValueFactory<User> valueFactory = new SpinnerValueFactory.ListSpinnerValueFactory<>(list);

        //重点就是 重写SpinnerValueFactory 实现类的convert方法
        valueFactory.setConverter(new StringConverter<User>() {
            @Override
            public String toString(User object) {
                return String.format("%s-%s", object.getName(), object.getAge());
            }

            @Override
            public User fromString(String string) {
                return null;
            }
        });
        listSpinner.setValueFactory(valueFactory);

        hBox.getChildren().addAll(listSpinner);
        primaryStage.setScene(new Scene(hBox));
        primaryStage.setWidth(600);
        primaryStage.setHeight(500);
        primaryStage.show();
    }


    private class User {
        private String name;
        private Integer age;

        public String getName() {
            return name;
        }

        public User setName(String name) {
            this.name = name;
            return this;
        }

        public Integer getAge() {
            return age;
        }

        public User setAge(Integer age) {
            this.age = age;
            return this;
        }
    }
}
